package com.lg.algorithm.leetcode;

public class FindMedianSortedArrays {

    static  int index1 = 0;
    static  int index2 = 0;
    public static void main(String[] args) {
        int[] nums1 = {1,2};
        int[] nums2 = {3,4};
        System.out.println(findMedianSortedArrays(nums1,nums2));
    }
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        double sum = 0;
        boolean oneNum = true;
        if ((nums1.length + nums2.length) % 2 == 0) {
            oneNum = false;
        }

        int pre = (nums1.length + nums2.length) / 2;

        if (pre > 0) {
            for (int i = 0; i < pre; i++) {
                sum = nextValue(nums1, nums2);
            }
        }

        if (oneNum) {
            sum = nextValue(nums1, nums2);
            return sum;
        }
        sum += nextValue(nums1, nums2);
        return sum / 2;
    }

    public static double nextValue(int[] nums1, int[] nums2) {
        double targetNum = -1;
        if (nums1.length > index1 && nums2.length > index2) {
            if (nums1[index1] < nums2[index2]) {
                targetNum = nums1[index1];
                index1++;
            } else  {
                targetNum = nums2[index2];
                index2++;
            }
            return targetNum;
        }

        if (nums1.length > index1) {
            targetNum = nums1[index1];
            index1++;
            return targetNum;
        }

        if ( nums2.length > index2) {
            targetNum = nums2[index2];
            index2++;
            return targetNum;
        }

        return 0;
    }
}
